package cn.wgx.modules.sys.services;

import cn.wgx.commons.storage.filetool.FileHeadType;
import cn.wgx.commons.util.IdGen;
import cn.wgx.commons.util.Servlets;
import cn.wgx.commons.util.StringUtils;
import cn.wgx.modules.base.services.BaseService;
import cn.wgx.modules.sys.entity.SysRes;
import cn.wgx.modules.sys.entity.SysResExample;
import cn.wgx.modules.sys.entity.SysUser;
import cn.wgx.modules.sys.entity.mapper.SysResMapper;
import cn.wgx.modules.sys.util.UserUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


@Service
public class SysResService extends BaseService<SysRes> {

    @Resource
    SysResMapper mapper;

    @Transactional(readOnly = true)
    public List<SysRes> getList(SysRes record, Boolean desc) {
		SysResExample example = new SysResExample();
		example.setOrderByClause("createDate " + (desc?"desc": "asc"));
		return mapper.selectByExample(example);
    }

    @Transactional(readOnly = true)
    public List<SysRes> getListByIds(List<Integer> ids) {
        if(ids == null || ids.isEmpty()){
            return emptyList;
        }
        List<Integer> uniList = getUniList(ids);
        if(!uniList.isEmpty()){
            SysResExample example = new SysResExample();
            SysResExample.Criteria criteria = example.createCriteria();
            criteria.andResource_idIn(uniList);
            List<SysRes> eduCourseAssignmentHis = mapper.selectByExample(example);
            return eduCourseAssignmentHis;
        }
        return null;
    }


    @Transactional(readOnly = true)
    public SysRes getOne(Integer id) {
		return mapper.selectByPrimaryKey(id);
    }

    @Transactional(readOnly = true)
    public SysRes getOneByMD5(String md5) {
        SysResExample example = new SysResExample();
        example.createCriteria().andMd5EqualTo(md5);
        List<SysRes> sysRes = mapper.selectByExample(example);
        if(sysRes != null && !sysRes.isEmpty()){
            return sysRes.get(0);
        }
        return null;
    }

    @Transactional(readOnly = true)
    public String getMD5ByPath(String path) {
        SysResExample example = new SysResExample();
        example.createCriteria().andUrlEqualTo(path);
        List<SysRes> sysRes = mapper.selectByExample(example);
        if(sysRes != null && !sysRes.isEmpty()){
            return sysRes.get(0).getMd5();
        }
        return null;
    }

    public int saveResource(String fileName, Long size, String path, String comeFrom, String md5,HttpServletRequest request){
            String originalFilename = fileName;
            int beginIndex = originalFilename.lastIndexOf('.');
            String preSuf = (beginIndex == -1)?"":originalFilename.substring(beginIndex+1);
            String suf = StringUtils.isNotBlank(preSuf)?preSuf.toLowerCase():"";
            if(request == null){
                request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            }
            String address = Servlets.getRemoteAddr(request);
            SysRes sysRes = new SysRes();
            sysRes.setOriginalName(originalFilename);
            sysRes.setUrl(path);
            sysRes.setSize(size);
            sysRes.setSuffix(suf);
            sysRes.setType(FileHeadType.getTypeByExt(suf)+"");
            sysRes.setComeFrom(comeFrom);
            sysRes.setAddress(address);
            sysRes.setMd5(md5);
            filter(sysRes, true);
            new Thread(() ->{
                mapper.insertSelective(sysRes);
            }).start();
        return 0;
    }


    public int saveResource(MultipartFile attach, String path, String comeFrom, String md5,HttpServletRequest request){
        if(StringUtils.isNotBlank(path) && attach != null){
            String originalFilename = attach.getOriginalFilename();
            long size = attach.getSize();
            int beginIndex = originalFilename.lastIndexOf('.');
            String preSuf = (beginIndex == -1)?"":originalFilename.substring(beginIndex+1);
            String suf = StringUtils.isNotBlank(preSuf)?preSuf.toLowerCase():"";
            if(request == null){
                request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            }
            String address = Servlets.getRemoteAddr(request);
            SysRes sysRes = new SysRes();
            sysRes.setOriginalName(originalFilename);
            sysRes.setUrl(path);
            sysRes.setSize(size);
            sysRes.setSuffix(suf);
            sysRes.setType(FileHeadType.getTypeByExt(suf)+"");
            sysRes.setComeFrom(comeFrom);
            sysRes.setAddress(address);
            sysRes.setMd5(md5);
            filter(sysRes, true);
            new Thread(() ->{
                mapper.insertSelective(sysRes);
            }).start();
        }
        return 0;
    }

    @Transactional
    public SysRes insertOne( SysRes record) {
        filter(record, true);
        mapper.insertSelective(record);
        return record;
    }

    @Transactional
    public int updateUserByUrl(String url) {
        SysResExample example = new SysResExample();
        example.createCriteria().andUrlEqualTo(url);
        SysRes record = new SysRes();
        record.setUsed(true);
        return mapper.updateByExampleSelective(record, example);
    }

    @Transactional
    public SysRes updateOne( SysRes record) {
        filter(record, false);
        mapper.updateByPrimaryKeySelective(record);
        return record;
    }


    @Transactional
    public int deleteOne( Integer id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    protected void filter(SysRes t, boolean isInsert) {
        if (isInsert) {
            if(StringUtils.isBlank(t.getMd5())){
                t.setMd5(IdGen.uuid());
            }
        } else {
            t.setMd5(null);
        }
        super.filter(t,isInsert);
    }
}